<template>
  <div style="background-color: #f5f5f5; padding: 24px">
    <PageHeader :ghost="false">
      <template #tags>
        <Form layout="inline" :model="searchValue" >
        <FormItem label="医院">
          <Select
            v-model:value="searchValue.hospitalId"
            show-search
            placeholder="请选择医院"
            style="width: 200px"
            :options="hospitalOption"
            :filter-option="filterOption"
            @focus="handleFocus"
            @blur="handleBlur"
            @change="handleChange"
          >
          </Select>
        </FormItem>
      
      </Form>
      </template>
      <template #extra>
          <Button type="primary" @click="onSubmit"> 查询 </Button>
       </template>
    </PageHeader>
  </div>
  <PageHeader :ghost ="false" title="科室列表">
    <template #extra>
      <Button type="primary" @click="handleOpenModal()">新增科室</Button>
    </template>
    <Table
    :columns="columns" 
    :data-source="data" 
    :row-selection="rowSelection"
    emptyText="暂时没有数据哦"
    bordered>
    <template #bodyCell="{ column, record ,index}">
      <template v-if="column.dataIndex === 'action'">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑科室',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除此科室',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDeleteRows.bind(null, record.id),
              },
            },
          ]"
        />
      </template>
      <template v-if="column.dataIndex === 'state'">
        <Switch 
        v-model:checked="record.state"
        :loading="switchLoading"
        @change="handleSwitchChange(record)"
        :checked-value="0" :un-checked-value="1"
        checked-children="已启用" un-checked-children="已禁用" />
      </template>
      <template v-if="column.dataIndex==='index'">
          {{index+1}}
      </template>
    </template>
  </Table>

  </PageHeader>
  <Modal
    v-model:visible="modalVisible"
    :title="title"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
  >
    <Form
    :model="formState"
    name="basic"
    :label-col="{ span: 5 }"
    :wrapper-col="{ span: 15 }"
    autocomplete="off"
    >
    <!-- <FormItem label="医院" name="hospitalId" :rule="[{required:true,message:'请选择医院'}]">
      <Select
            v-model:value="formState.hospitalId"
            show-search
            placeholder="请选择医院"
            :options="hospitalOption"
            :filter-option="filterOption"
            @focus="handleFocus"
            @blur="handleBlur"
            @change="handleModelChange"
          >
          </Select>
    </FormItem>
    <FormItem label="科室" name="pid" :rule="[{required:true,message:'请选择科室'}]">
      <Select v-model:value="formState.pid"
      :disabled="!cascaderVisable"
      placeholder="请选择科室"
      :option="cascaderOption"
      >
       
      </Select>
    </FormItem> -->
    <FormItem label="医院/科室" name="">
        <Cascader v-model:value="formState.ids" :option="options" />
    </FormItem>
      <FormItem label="科室名" name="deptName"  :rule="[{required:true,message:'请选输入科室名'}]" >
      <Input v-model:value="formState.deptName" 
     />
    </FormItem>
    <FormItem
    name="formState.state" 
    label="状态" 
    :rule="[{required:true,message:'请选择状态'}]">
    <Switch 
        v-model:checked="formState.state"
        :checked-value="0" :un-checked-value="1"
        checked-children="启用" un-checked-children="禁用" />
    </FormItem>
    </Form>
  </Modal>
</template>

<script lang="ts">
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align:'center',
      width:120
    },
    {
      title: '科室名',
      dataIndex: 'deptName',
      key: 'deptName',
      align:'center',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      width:200,
      align:'center',
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      width:120,
      align:'center',
    },
    {
      align:'center',
      title: '操作',
      dataIndex: 'action',
      width:120
    },
  ]

  interface DataItem {
    id:string,
    deptName: string
    gmtCreate: string
    state: number,
    pid:string,
    children?: DataItem[]
  }


  const rowSelection = ref({
    checkStrictly: false,
    onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
    },
    onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
      console.log(record, selected, selectedRows)
    },
    onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
      console.log(selected, selectedRows, changeRows)
    },
  })

  import { defineComponent, onMounted, reactive, ref, toRaw } from 'vue'
  import { BasicTable, TableAction } from '/@/components/Table'
  import { Input,Cascader,Modal,Space, Switch, Table, PageHeader, Select, Form, FormItem, Button, message } from 'ant-design-vue'
  import { listOptionHospital } from '/@/api/demo/hospital'
  import { DepartmentItem, ListDepartmentParams } from '/@/api/demo/model/departmentModel'
  import { listAllHospitalAnd1Department, listDepartment, updateState } from '/@/api/demo/department'
import { useI18n } from '/@/hooks/web/useI18n'
import { useMessage } from '/@/hooks/web/useMessage'
  export default defineComponent({
    name: 'DepartmentManagement',
    components: {
      Input,
      Cascader,
      FormItem,
      Form,
      Button,
      BasicTable,
      TableAction,
      Space,
      Switch,
      Table,
      PageHeader,
      Select,
      Modal,
    },
    setup() {
      initCascader()
      const options = ref([])
      
      const cascaderVisable = ref(false)
      const confirmLoading = ref(false)
      const modalVisible = ref(false)
      const {t} = useI18n()
      const {createErrorModal} = useMessage()
      const formState = ref({})
      function handleEdit(record,e) {
        
      }
      function handleDeleteRows() {}
      const searchValue: ListDepartmentParams = reactive({})
      const data = ref([])
      handleList()
      const hospitalOption = ref([])
      const selectValue = ref('')
      const departmentList = ref<DepartmentItem[]>([])
      const switchLoading = ref(false)
      const title = ref('新增科室')
      
      handleHospitalOption()
      const handleChange = (value: string) => {
        console.log(`selected ${value}`)
      }
      const handleBlur = () => {
        console.log('blur')
      }
      const handleFocus = () => {}
      const filterOption = (input: string, option: any) => {
        return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
      function handleHospitalOption() {
        hospitalOption.value = []
        listOptionHospital()
          .then((res) => {
            res?.forEach((element) => {
              hospitalOption.value.push({ value: element.id, label: element.name })
            })
            searchValue.hospitalId = res[0].id
            console.log('hospitalId', searchValue.hospitalId)
            selectValue.value = res[0].id
          })
          .catch()
          .finally()
      }
      function onSubmit() {
        listDepartment(toRaw(searchValue))
          .then((res) => {
            departmentList.value = res
            console.log('onSubmit', res)
          })
          .catch((err) => {})
      }
      function handleSwitchChange(record){
        switchLoading.value = true
        const params = {
          id:record.id,
          state:record.state
        }
        updateState(params).then(() => {
              message.success(t('sys.api.successMessage'))
            })
            .catch((error) => {
              createErrorModal({
                title: t('sys.api.errorTip'),
                content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
              })
            })
            .finally(()=>{
              switchLoading.value = false
            })  
    }
    function handleList(){
      listDepartment({hospitalId:searchValue.hospitalId}).then(res=>{
        data.value = res
      }
      ).catch((error) => {
              createErrorModal({
                title: t('sys.api.errorTip'),
                content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
              })
            })
    }
    function handleOk(){
      
    }
    function handleOpenModal(isUpdate=false,record){
      if(isUpdate){
        formState.value = record
        title.value = '更新科室'
      }
      modalVisible.value = true
    }

    function handleModelChange(value){
      cascaderOption.value.length=0
      cascaderVisable.value = false
      cascaderOption.value.push({label:'无',value:'0'})
      listDepartment({hospitalId:value}).then((res)=>{
        console.log('res',res);
        res.forEach(element => {
          const optionItem = {
            label:element.deptName,
            value:element.id,
          }
          cascaderOption.value.push(optionItem)
          console.log('foreach',optionItem);
          
        });
        cascaderVisable.value = true
        console.log('cascader',cascaderOption)
      })
      // cascaderOptio
    }
    onMounted(()=>{
        initCascader()
    })
    function initCascader(){
      listAllHospitalAnd1Department().then(res=>{
        console.log('res',res);
        options.value = res
        
      })
    }
    return {options,
      cascaderVisable,
      handleModelChange,
      handleOk,
      confirmLoading,
      title,
      handleList,
        switchLoading,
        handleDeleteRows,
        handleEdit,
        onSubmit,
        filterOption,
        handleFocus,
        handleBlur,
        handleChange,
        hospitalOption,
        selectValue,
        data,
        columns,
        rowSelection,
        searchValue,
        handleSwitchChange,
        modalVisible,
        formState,
        handleOpenModal
      }
  }})
</script>

<style></style>
